package com.exampl.springstack.common.utils;

import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author Qiangfanghao
 *
 * 实体类pojo-vo-bto转换工具
 *
 */
public class BeanHelper {

    /**
     *
     * @param source 源实体类
     * @param target 转换目标实体类
     * @param <T>
     * @return
     */
    public static <T> T copyProperties(Object source, Class<T> target){
        try {
            T t = target.newInstance();
            BeanUtils.copyProperties(source, t);
            return t;
        } catch (Exception e) {
            //建议抛自定义异常
            throw new RuntimeException();
        }
    }

    /**
     *
     * @param sourceList 源List 实体类
     * @param target  转换List 目标实体类
     * @param <T>
     * @return
     */
    public static <T> List<T> copyWithCollection(List<?> sourceList, Class<T> target){
        try {
            return sourceList.stream().map(s -> copyProperties(s, target)).collect(Collectors.toList());
        } catch (Exception e) {
            //建议抛自定义异常
            throw new RuntimeException();
        }
    }

    /**
     *
     * @param sourceList 源List 实体类
     * @param target    转换set 实体类
     * @param <T>
     * @return
     */
    public static <T> Set<T> copyWithCollectionToSet(List<?> sourceList, Class<T> target){
        try {
            return sourceList.stream().map(s -> copyProperties(s, target)).collect(Collectors.toSet());
        } catch (Exception e) {
            e.printStackTrace();
            //建议抛自定义异常
            throw new RuntimeException();
        }
    }

    /**
     *
     * @param sourceList 源set 实体类
     * @param target    转换set 实体类
     * @param <T>
     * @return
     */
    public static <T> Set<T> copyWithCollection(Set<?> sourceList, Class<T> target){
        try {
            return sourceList.stream().map(s -> copyProperties(s, target)).collect(Collectors.toSet());
        } catch (Exception e) {
            e.printStackTrace();
            //建议抛自定义异常
            throw new RuntimeException();
        }
    }

    /**
     * obj -> List
     * @param obj
     * @param cla
     * @param <T>
     * @return
     */
    public static <T> List<T> objToList(Object obj, Class<T> cla){
        List<T> list = new ArrayList<T>();
        if (obj instanceof ArrayList<?>) {
            for (Object o : (List<?>) obj) {
                list.add(cla.cast(o));
            }
            return list;
        }
        return null;
    }

}
